package cn.stylefeng.guns.core.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.GZIPInputStream;


/**
 * 获取聚水潭 采购入库单
 * @author zcx
 */
public class justCgrkApi {
	private static final String SIGN_METHOD_MD5 = "md5";
    private static final String CHARSET_UTF8 = "utf-8";
    private static final String CONTENT_ENCODING_GZIP = "gzip";

    // TOP服务地址，正式环境需要设置为https://openapi.jushuitan.com
    private static final String serverUrl = "https://openapi.jushuitan.com/open/purchasein/query";//正式环境	请求地址
//    private static final String serverUrl = "https://dev-api.jushuitan.com/open/purchasein/query";//测试环境	请求地址

    private static final String serverUrlNew = "https://openapi.jushuitan.com/open/webapi/wmsapi/purchasein/purchaseinquery";

    private static final String appKey = "b0b7d1db226d4216a3d58df9ffa2dde5"; // 测试应用的appKey
    private static final String appSecret = "99c4cef262f34ca882975a7064de0b87"; // 测试应用的appSecret
    private static final String accessToken = "8db141b6d724211b28d2eff2c93fe918"; // 测试授权accessToken

    public static void main(String[] args) throws Exception {
        //System.out.println(getSellerItem(appKey,appSecret,accessToken,"2023-03-07 00:00:00","2023-03-07 23:59:59","1"));
        Map<String, String> params = new HashMap<String, String>();
        // 公共参数
        params.put("app_key", "c8e0d3e0782941e38f8da4d2f5a192f3");
        params.put("access_token", "6fbd5a28cca04a42a42aba6fa11601b1");
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        params.put("biz","{}");
        // 签名参数
//
        System.out.println(params);
        System.out.println(signTopRequest( params, "99f4816e1dc543c78acefb79c8c66337", SIGN_METHOD_MD5));
    }

    public static String getSellerItem(String appKey,String appSecret,String accessToken,String modified_begin,String modified_end,String page_index) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        // 公共参数
        params.put("app_key", appKey);
        params.put("access_token", accessToken);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        params.put("biz","{modified_begin:'"+modified_begin+"',modified_end:'"+modified_end+"',page_index:"+Integer.parseInt(page_index)+",page_size:"+50+"}");
        // 签名参数
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));
        // 调用API
        return callApi(new URL(serverUrl), params);
    }

    /**
     *
     * @param appKey
     * @param appSecret
     * @param accessToken
     * @param modified_begin
     * @param modified_end
     * @param page_index
     * @return
     * @throws IOException
     */
    public static String getSellerItemNew(String appKey,String appSecret,String accessToken,String modified_begin,String modified_end,String page_index) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        // 公共参数
        params.put("app_key", appKey);
        params.put("access_token", accessToken);
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        params.put("biz",
                "{modified_begin:'"+modified_begin+"'," +
                        "modified_end:'"+modified_end+"'," +
                        "date_type:"+Integer.parseInt("2")+"," +

                        "page_index:"+Integer.parseInt(page_index)+"," +

                        "page_size:"+50+"}");
        // 签名参数
        params.put("sign", signTopRequest(params, appSecret, SIGN_METHOD_MD5));
        // 调用API
        return callApi(new URL(serverUrl), params);
    }
    /**
     * 对TOP请求进行签名。
     */
    private static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        if (SIGN_METHOD_MD5.equals(signMethod)) {
            query.append(secret);
        }
        for (String key : keys) {
            String value = params.get(key);
            if (isNotEmpty(key) && isNotEmpty(value)) {
                query.append(key).append(value);
            }
        }
        return createSign(query.toString());
    }

    /**
     * 生成新sign
     *
     * @param str 字符串
     * @return String
     */
    private static String createSign(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(SIGN_METHOD_MD5);
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            int i = 0;
            while (i < j) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
                i++;
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }


    private static String callApi(URL url, Map<String, String> params) throws IOException {
        String query = buildQuery(params, CHARSET_UTF8);
        byte[] content = {};
        if (query != null) {
            content = query.getBytes(CHARSET_UTF8);
        }

        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Host", url.getHost());
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + CHARSET_UTF8);
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

        return rsp;
    }

    private static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder query = new StringBuilder();
        Set<Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;

        for (Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 忽略参数名或参数值为空的参数
            if (isNotEmpty(name) && isNotEmpty(value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }

                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }

        return query.toString();
    }

    private static String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        if (conn.getResponseCode() < 400) {
            String contentEncoding = conn.getContentEncoding();
            if (CONTENT_ENCODING_GZIP.equalsIgnoreCase(contentEncoding)) {
                return getStreamAsString(new GZIPInputStream(conn.getInputStream()), charset);
            } else {
                return getStreamAsString(conn.getInputStream(), charset);
            }
        } else {// Client Error 4xx and Server Error 5xx
            throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage());
        }
    }

    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            Reader reader = new InputStreamReader(stream, charset);
            StringBuilder response = new StringBuilder();

            final char[] buff = new char[1024];
            int read = 0;
            while ((read = reader.read(buff)) > 0) {
                response.append(buff, 0, read);
            }

            return response.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    private static String getResponseCharset(String ctype) {
        String charset = CHARSET_UTF8;

        if (isNotEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (isNotEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }

        return charset;
    }

    private static boolean isNotEmpty(String value) {
        int strLen;
        if (value == null || (strLen = value.length()) == 0) {
            return false;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(value.charAt(i)) == false)) {
                return true;
            }
        }
        return false;
    }
}
